# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 服务流程
"""
from fastapi import APIRouter, Request, Query

from config import Config
from project.core.base import Select
from project.core.function import json_response
from project.lib.decorator import api_common, exec_duration
from project.model.database.agent import Agent
from project.model.database.knowledge import KnowledgeData, KnowledgeDetail


knowledge_router = APIRouter(prefix='/b', tags=['backend.knowledge'])


@knowledge_router.get('/knowledge/detail/code/list', summary='得到知识库详情编号列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_knowledge_detail_list(request: Request,
                                    agent_code: str = Query(None, title='智能体编号'),
                                    session=None):
    """
    **desc**: 得到知识库详情编号列表

    **url**: http(s)://{0}.udicaria.com.udicaria.com/b/agent/knowledge/detail/code/list

    **method**: GET

    **params**:

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data:
            exec_time: 接口后端处理时长
        }
    """
    agent = await Agent.fetch_one(session, wheres=(Agent.code == agent_code, ~Agent.is_deleted))
    if not agent:
        return json_response()

    knowledge_details = await Select(selects=(KnowledgeDetail),
                                     joins=((KnowledgeData, KnowledgeData.id == KnowledgeDetail.knowledge_data_id),),
                                     wheres=(KnowledgeData.knowledge_id.in_(agent.knowledge_ids),
                                             ~KnowledgeData.is_deleted,
                                             ~KnowledgeDetail.is_deleted)).fetch_all(session)
    knowledge_detail_codes = [v.code for v in knowledge_details]

    return json_response(data=knowledge_detail_codes)
